package cn.exrick.xboot.modules.content.controller;

import cn.exrick.xboot.common.redis.RedisTemplateHelper;
import cn.exrick.xboot.common.utils.PageUtil;
import cn.exrick.xboot.common.utils.RestTemplateUtil;
import cn.exrick.xboot.common.utils.ResultUtil;
import cn.exrick.xboot.common.vo.PageVo;
import cn.exrick.xboot.common.vo.Result;
import cn.exrick.xboot.config.properties.RestTemplateProperties;
import cn.exrick.xboot.modules.base.entity.Role;
import cn.exrick.xboot.modules.base.entity.RoleDepartment;
import cn.exrick.xboot.modules.base.entity.RolePermission;
import cn.exrick.xboot.modules.base.entity.UserRole;
import cn.exrick.xboot.modules.content.entity.*;
import cn.exrick.xboot.modules.content.service.*;
import cn.exrick.xboot.modules.content.service.mybatis.IHontUserRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;

import javax.persistence.Id;
import java.util.Date;
import java.util.List;
import java.util.Set;


/**
 * @author Exrick
 */
@Slf4j
@RestController
@Api(description = "角色管理接口")
@RequestMapping("/xboot/hontRole")
@Transactional
public class

HontRoleController{

    @Autowired
    private HontRoleService hontRoleService;
    @Autowired
    private HontUserRoleService hontUserRoleService;
    @Autowired
    private IHontUserRoleService iHontUserRoleService;
    @Autowired
    private HontRolePermissionService hontRolePermissionService;
    @Autowired
    private HontPermissionService hontPermissionService;
    @Autowired
    private RedisTemplateHelper redisTemplateHelper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private HontRoleDepartmentService hontRoleDepartmentService;
    @Autowired
    private RestTemplateProperties restTemplateProperties;

    @RequestMapping(value = "/getAllList",method = RequestMethod.GET)
    @ApiOperation(value = "获取全部角色")
    public Result<Object> roleGetAll(){
        List<HontRole> list = hontRoleService.getAll();
        return ResultUtil.data(list);
    }

    @RequestMapping(value = "/getAllByPage",method = RequestMethod.GET)
    @ApiOperation(value = "分页获取角色")
    public Result<Page<HontRole>> getRoleByPage(PageVo page){

        Page<HontRole> list = hontRoleService.findAll(PageUtil.initPage(page));
        for(HontRole hontRole : list.getContent()){
            // 角色拥有权限
            List<HontRolePermission> permissions = hontRolePermissionService.findByHontRoleId(hontRole.getId());
            for(int i=0;i<permissions.size();i++){
                HontPermission permission = hontPermissionService.get(permissions.get(i).getHontPermissionId());
                if(permission!=null){
                    permissions.get(i).setHontPermissionLevel(permission.getLevel());
                }
            }
            hontRole.setPermissions(permissions);
            // 角色拥有数据权限
            List<HontRoleDepartment> departments = hontRoleDepartmentService.findByHontRoleId(hontRole.getId());
            hontRole.setDepartments(departments);
        }
        return new ResultUtil<Page<HontRole>>().setData(list);
    }

    @RequestMapping(value = "/editRolePerm",method = RequestMethod.POST)
    @ApiOperation(value = "编辑角色分配菜单权限")
    public Result<Object> editRolePerm(@RequestParam String roleId,
                                       @RequestParam(required = false) String[] permIds){

        //删除其关联权限
        hontRolePermissionService.deleteByHontRoleId(roleId);
        //分配新权限
        for(String permId : permIds){
            HontRolePermission rolePermission = new HontRolePermission();
            rolePermission.setHontRoleId(roleId);
            rolePermission.setHontPermissionId(permId);
            hontRolePermissionService.save(rolePermission);
        }
        //手动批量删除缓存
        Set<String> keysUser = redisTemplateHelper.keys("hontUser:" + "*");
        redisTemplate.delete(keysUser);
        Set<String> keysUserRole = redisTemplateHelper.keys("hontUserRole:" + "*");
        redisTemplate.delete(keysUserRole);
        Set<String> keysUserPerm = redisTemplateHelper.keys("hontUserPermission:" + "*");
        redisTemplate.delete(keysUserPerm);
        Set<String> keysUserMenu = redisTemplateHelper.keys("hontpermission::hontUserMenuList:*");
        redisTemplate.delete(keysUserMenu);
        return ResultUtil.data(null);
    }
    @RequestMapping(value = "/editRoleDep",method = RequestMethod.POST)
    @ApiOperation(value = "编辑角色分配数据权限")
    public Result<Object> editRoleDep(@RequestParam String roleId,
                                      @RequestParam Integer dataType,
                                      @RequestParam(required = false) String[] depIds){

        HontRole r = hontRoleService.get(roleId);
        r.setDataType(dataType);
        hontRoleService.update(r);
        // 删除其关联数据权限
        hontRoleDepartmentService.deleteByHontRoleId(roleId);
        // 分配新数据权限
        for(String depId : depIds){
            HontRoleDepartment roleDepartment = new HontRoleDepartment();
            roleDepartment.setHontRoleId(roleId);
            roleDepartment.setHontDepartmentId(depId);
            hontRoleDepartmentService.save(roleDepartment);
        }
        // 手动删除相关缓存
        Set<String> keys = redisTemplateHelper.keys("hontDepartment:" + "*");
        redisTemplate.delete(keys);
        Set<String> keysUserRole = redisTemplateHelper.keys("hontUserRole:" + "*");
        redisTemplate.delete(keysUserRole);

        return ResultUtil.data(null);
    }
    @RequestMapping(value = "/setDefault",method = RequestMethod.POST)
    @ApiOperation(value = "设置或取消默认角色")
    public Result<Object> setDefault(@RequestParam String id,
                                     @RequestParam Boolean isDefault){

        HontRole role = hontRoleService.get(id);
        if(role==null){
            return ResultUtil.error("角色不存在");
        }
        List<HontRole> byDefaultRole = hontRoleService.findByDefaultRole(true);
        for (HontRole role1 : byDefaultRole) {
            role1.setDefaultRole(false);
        }
        role.setDefaultRole(isDefault);
        hontRoleService.update(role);
        return ResultUtil.success("设置成功");
    }
    @RequestMapping(value = "/save",method = RequestMethod.POST)
    @ApiOperation(value = "保存数据")
    public Result<HontRole> save(HontRole role) throws Exception {
        role.setDefaultRole(false);
        HontRole r = hontRoleService.save(role);
        /*String url = restTemplateProperties.getUrl();
        String restUrl = url +  "/rest/group/save";
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        params.add("id",r.getId());
        params.add("name",r.getName());
        Result<Object> objectResult = RestTemplateUtil.sendPostRequest(restUrl, params);
        if (objectResult.getCode() != 200){
            throw new Exception("远程调用失败");
        }*/
        return new ResultUtil<HontRole>().setData(r);
    }
    @RequestMapping(value = "/delAllByIds/{ids}",method = RequestMethod.DELETE)
    @ApiOperation(value = "批量通过ids删除")
    public Result<Object> delByIds(@PathVariable String[] ids) throws Exception {


        for(String id:ids){
            List<HontUserRole> list = hontUserRoleService.findByRoleId(id);
            if(list!=null&&list.size()>0){
                return ResultUtil.error("删除失败，包含正被用户使用关联的角色");
            }
        }
        for(String id:ids){
            hontRoleService.delete(id);
            //删除关联菜单权限
            hontRolePermissionService.deleteByHontRoleId(id);
            //删除关联数据权限
            hontRoleDepartmentService.deleteByHontRoleId(id);
        }
        /*String updateUrl = restTemplateProperties.getUrl();
        String restRoleUrl = updateUrl +  "/rest/dataSynchronization/delete";
        MultiValueMap<String, Object> roleParams = new LinkedMultiValueMap<>();
        StringBuffer buffer=new StringBuffer();
        for (int i=0;  i < ids.length; i++) {
            if(i==0){
                buffer.append(ids[0]);
            }else{
                buffer.append(","+ids[0]);
            }
        }
        roleParams.add("id",buffer.toString());
        Result<Object> objectUpdateResult = RestTemplateUtil.sendPostRequest(restRoleUrl, roleParams);
        if (objectUpdateResult.getCode() != 200){
            throw new Exception("远程调用失败");
        }*/

        return ResultUtil.success("删除成功");
    }
    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    @ApiOperation(value = "更新数据")
    public Result<HontRole> edit(HontRole entity) throws Exception {

        HontRole role = hontRoleService.get(entity.getId());
        if (role != null){
            Date createTime = role.getCreateTime();
            role.setCreateTime(createTime);
            role.setName(entity.getName());
            role.setDescription(entity.getDescription());
            role.setLevel(entity.getLevel());
        }
        hontRoleService.update(role);
//        String url = restTemplateProperties.getUrl();
//        String restUrl = url +  "/rest/dataSynchronization/updateGroup";
//        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
//        params.add("id",role.getId());
//        params.add("roleName",role.getName());
//        Result<Object> objectResult = RestTemplateUtil.sendPostRequest(restUrl, params);
//        if (objectResult.getCode() != 200){
//            throw new Exception("远程调用失败");
//        }
        //手动批量删除缓存
        Set<String> keysUser = redisTemplateHelper.keys("hontUser:" + "*");
        redisTemplate.delete(keysUser);
        Set<String> keysUserRole = redisTemplateHelper.keys("hontUserRole:" + "*");
        redisTemplate.delete(keysUserRole);
        return new ResultUtil<HontRole>().setData(role);
    }

    @RequestMapping(value = "/getHontRoleByTitle", method = RequestMethod.GET)
    @ApiOperation(value = "模糊搜索部门")
    public Result<List<HontRole>> searchHontRoleList(String title){
        List<HontRole> byNameLike = hontRoleService.findByNameLike("%" + title + "%");
        return new ResultUtil<List<HontRole>>().setData(byNameLike);
    }
    @RequestMapping(value = "/getHontRoleByUserId", method = RequestMethod.GET)
    @ApiOperation(value = "模糊搜索部门")
    public Result<List<HontRole>> getHontRoleByUserId(String userId){
        List<HontRole> byNameLike = iHontUserRoleService.findByUserId(userId);
        return new ResultUtil<List<HontRole>>().setData(byNameLike);
    }

}
